package com.quickcode.example.threadpool;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * Created by 张波 on 2019/10/25.
 */
@Slf4j
public class ThreadPoolExample2 {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(2);
//        scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
//            @Override
//            public void run() {
//                log.info("hello");
//            }
//        },1,2,TimeUnit.SECONDS);

        // 在上一个任务执行完成后，等待延迟时间开始执行下一个任务
        scheduledExecutorService.scheduleWithFixedDelay(new Runnable() {
            @Override
            public void run() {
                log.info("hello");
//                throw new RuntimeException();
                try {
                    TimeUnit.SECONDS.sleep(3);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },1,2, TimeUnit.SECONDS);
        log.info("start");
        // 如果下一个任务时间到了，但上一个任务没执行完，则在执行完上一个任务上马上执行下一个任务
        scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                log.info("world");
                try {
                    TimeUnit.SECONDS.sleep(3);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },1,2,TimeUnit.SECONDS);
    }

}
